package com.alavente.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.alavente.objects.Client;

public class HibernateClientDAO extends HibernateAbstractDAO<Client> implements GenericDAOInterface<Client> {

	public Client getByLogin(String login) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Client client = null;
		
		try {
			transaction = session.beginTransaction();			
			//client = (Client) session.get(Client.class, login);
			List<Client> list = session.createQuery("from Client client where client.login='" + login + "'").list();
			if (!list.isEmpty())
				client = list.get(0);
			transaction.commit();
		} 
		catch (HibernateException he) {
			he.printStackTrace();
			if(transaction != null) {
				try { transaction.rollback();} catch(HibernateException he2) {
					he2.printStackTrace(); }
				}
		}
		finally {
			if(session != null) {
				try { session.close();} catch(HibernateException he) {
					he.printStackTrace(); }
			}
		}
		
		return client;
	}
	
	public Client getById(int id) {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Client client = null;
		
		try {
			transaction = session.beginTransaction();			
			client = (Client) session.get(Client.class, id);			
			transaction.commit();
		} 
		catch (HibernateException he) {
			he.printStackTrace();
			if(transaction != null) {
				try { transaction.rollback();} catch(HibernateException he2) {
					he2.printStackTrace(); }
				}
		}
		finally {
			if(session != null) {
				try { session.close();} catch(HibernateException he) {
					he.printStackTrace(); }
			}
		}
		
		return client;
	}
}